package com.wbdgj.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.CardView;
import android.view.KeyEvent;
import android.view.View;

import com.wbdgj.R;
import com.wbdgj.base.BaseActivity;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.base.BaseWhiteActivity;
import com.wbdgj.http.HttpVersionAdapter;
import com.wbdgj.http.OnNoResponseListener;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.ResultModel;
import com.wbdgj.model.ResultRefeshModel;
import com.wbdgj.model.ResultVersionModel;
import com.wbdgj.ui.home.HomeFragment;
import com.wbdgj.ui.login.LoginActivity;
import com.wbdgj.ui.login.ZhuFragment;
import com.wbdgj.ui.mine.MineFragment;
import com.wbdgj.ui.mine.VerifiedActivity;
import com.wbdgj.ui.near.NearFragment;
import com.wbdgj.ui.news.NewsFragment;
import com.wbdgj.utils.LogUtils;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.dialog.ConfirmDialog;
import com.wbdgj.views.EasyRadioGroup;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

/**
 * Created by Administrator on 2018/3/10.
 */

public class MainActivity extends BaseWhiteActivity{

    private static EasyRadioGroup easyRadioGroup;

    HomeFragment HomeFragment;
    NearFragment NearFragment;
    NewsFragment NewsFragment;
    MineFragment MineFragment;

    List<Fragment> fragments;
    Fragment currentFragment;
    private SharedPreferences sharedPreferences;
    private long mkeyTime;
    public Context context = this;

    private String versionCode;
    private int sm;
    @Override
    protected int getLayoutResId() {
        return R.layout.ui_main;
    }

    @Override
    public void initView() {
        easyRadioGroup = (EasyRadioGroup) findViewById(R.id.home_bottom);
        fragments = new ArrayList<>();
        //初始化Fragment
        fragments.add(HomeFragment = (HomeFragment) Fragment.instantiate(this, HomeFragment.class.getName()));
        fragments.add(NearFragment = (NearFragment) Fragment.instantiate(this, NearFragment.class.getName()));
        fragments.add(NewsFragment = (NewsFragment) Fragment.instantiate(this, NewsFragment.class.getName()));
        fragments.add(MineFragment = (MineFragment) Fragment.instantiate(this, MineFragment.class.getName()));
        currentFragment = HomeFragment;
        switchFragment(null, HomeFragment);
        easyRadioGroup.setOnTabSelectListener(new EasyRadioGroup.OnTabSelectListener() {
            @Override
            public void onSelect(View view, int position) {

                switchFragment(currentFragment, fragments.get(position));
                currentFragment = fragments.get(position);

            }
        });

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CardView cardView = (CardView) easyRadioGroup.getParent();
            reflectBg(cardView);
        }
        sm = getIntent().getIntExtra("sm", 0);
        if (sm == 1){
            launch(VerifiedActivity.class);
        }
        isUpdate();
    }

    private void reflectBg(final CardView cardView) {

        try {
            Field field = cardView.getClass().getDeclaredField("mCardViewDelegate");
            field.setAccessible(true);
            Object object = field.get(cardView);
            Method method = object.getClass().getDeclaredMethod("setShadowPadding", int.class, int.class, int.class, int.class);
            method.invoke(object, 0, 0, 0, 0);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        cardView.postDelayed(new Runnable() {
            @Override
            public void run() {
                Drawable drawable = cardView.getBackground();
                try {
                    Field field = drawable.getClass().getDeclaredField("mCardBounds");
                    field.setAccessible(true);
                    RectF rectF = (RectF) field.get(drawable);
                    rectF.set(cardView.getLeft(), cardView.getTop(), cardView.getRight(), cardView.getBottom());
                    drawable.invalidateSelf();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }, 100);
    }


    public static void  choiceFragment(int tab){
        easyRadioGroup.setTabCurrenItem(tab);
    }

    /**
     * 切换Fragment
     *
     * @param from
     * @param to
     */
    public void  switchFragment(Fragment from, Fragment to) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (from == null) {
            transaction.add(R.id.frag_container, to);
        } else {
            if (!getSupportFragmentManager().getFragments().contains(to)) {
                transaction.add(R.id.frag_container, to);
            }
            transaction.hide(from);
            transaction.show(to);
        }
        transaction.commitAllowingStateLoss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if((System.currentTimeMillis() - mkeyTime) > 2000){
                mkeyTime = System.currentTimeMillis();
                showToast("再按一次退出程序");
            }else{
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 判断是否有更新
     */
    private void isUpdate() {

        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        versionCode = packageInfo.versionName;
        Call<ResultRefeshModel<ResultVersionModel>> call = HttpVersionAdapter.getSerives().version();
        call.enqueue(new OnNoResponseListener<ResultRefeshModel<ResultVersionModel>>(context) {
            @Override
            protected void onSuccess(final ResultRefeshModel<ResultVersionModel> followModelBaseResultModel) {
                if (followModelBaseResultModel.getCode() == 0){
                    LogUtils.loge("appVersion="+versionCode);
                    double version01 = Double.parseDouble(versionCode);
                    double version02 = Double.parseDouble(followModelBaseResultModel.getData().getBuildVersion());
                    if(version02>version01){
                        startActivity(new Intent(context, UpdateDialogActivity.class).putExtra("content", followModelBaseResultModel.getData().getBuildUpdateDescription()).putExtra("url", followModelBaseResultModel.getData().getDownloadURL()));
//                        final ConfirmDialog confirmDialog = new ConfirmDialog(context, "有最新的版本发布，确定更新吗？", 1);
//                        confirmDialog.show();
//                        confirmDialog.setCanceledOnTouchOutside(false);
//                        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
//                            @Override
//                            public void doConfirm() {
//                                confirmDialog.dismiss();
//                                Intent intent = new Intent();
//                                intent.setAction("android.intent.action.VIEW");
//                                Uri content_url = Uri.parse(followModelBaseResultModel.getData().getDownloadURL());
//                                intent.setData(content_url);
//                                startActivity(intent);
//                            }
//
//                            @Override
//                            public void doCancel() {
//                                confirmDialog.dismiss();
//                            }
//                        });

                    }
                }


            }

            @Override
            protected void onFailure(String msg) {
                super.onFailure(msg);
            }
        });

    }
}
